<?php
/**
 * Created by PhpStorm.
 * User: Hanson
 * Date: 2016/9/25
 * Time: 23:08
 */

namespace App\Repository;


use App\Model\Role;
use App\Model\RoleUser;

class RoleUserRepository
{
    protected $role;

    public function __construct(Role $role)
    {
        $this->role = $role;
    }

    /**
     * 获取所有角色
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function all()
    {
        return Role::all();
    }

    /**
     * 增加角色
     *
     * @param $name string 角色名
     * @param null $displayName string 角色
     * @param null $description string 角色描述
     * @return bool|\Illuminate\Database\Eloquent\Model
     */
    public function add($name, $displayName = null, $description = null)
    {

        if(!$name) return false;

        return Role::updateOrCreate(['name' => $name], ['display_name' => $displayName, 'description' => $description]);
    }

    public function delete($id)
    {
        return Role::destroy($id);
    }

    public function updateByAdmin($adminId, Array $roles)
    {
        $roles = array_unique($roles);

        RoleUser::whereAdminId($adminId)->delete();

        foreach ($roles as $role) {
            RoleUser::create(['admin_id' => $adminId, 'role_id' => $role]);
        }
    }

    public function findByAdmin($adminId, $column = ['*'])
    {
        return RoleUser::where('admin_id', $adminId)->get($column);
    }

    public function getAdminsByRepair($roleName)
    {
        return $this->role->Where('name', $roleName)->first()->users()->with([
            'user' => function($query){
                $query->select(['number', 'name']);
            }
        ])->get(['id', 'number']);
    }
}